package com.shycloud.mido.music.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiniu.storage.model.FileInfo;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.service.ShyMember;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.music.domain.*;
import com.shycloud.mido.music.mapper.MisMusicCollectionMapper;
import com.shycloud.mido.music.mapper.MisMusicMapper;
import com.shycloud.mido.music.mapper.MisMusicMemberStarMapper;
import com.shycloud.mido.music.mapper.MisRecentPlayedMapper;
import com.shycloud.mido.music.service.*;
import com.shycloud.mido.music.service.impl.MisUserBuyCollectionService;
import com.shycloud.mido.music.util.CommonString;
import com.shycloud.mido.music.vo.*;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author nianhua.jiang
 * @description 曲库 Controller
 * @date 2020/4/22
 */
@RestController
@AllArgsConstructor
@RequestMapping("/music")
@ApiOperation(value = "单曲模块")
public class MusicController {

	/** 曲集 service */
	private MisMusicCollectionService misMusicCollectionService;
	/** 曲目 service */
	private MisMusicService misMusicService;
	private MisMusicMapper musicMapper;
	/** 收藏曲目 service */
	private MisUserMusicService userMusicService;
	/** 收藏曲集 service */
	private MisUserCollectionService userCollectionService;
	/** 自建曲集 service */
	private MisMyCollectionService myCollectionService;
	/** 曲集购买 service */
	private MisUserBuyCollectionService buyCollectionService;
	/** 引导视频模块 service */
	private MisGuideVideoService guideVideoService;
	/** 七牛云 oss */
	private MinioTemplate minioTemplate;
	/** 自建曲集与曲目关系 service */
	private MisMyCollectionMusicService misMyCollectionMusicService;
	/** 曲集Mapper */
	private MisMusicCollectionMapper collectionMapper;
	/** 最近播放列表Mapper */
	private MisRecentPlayedMapper recentPlayedMapper;
	/** 排行榜业务 mapper */
	private MisMusicMemberStarMapper starMapper;

	/**
	 * 添加曲目（更新操作）
	 *
	 * @param misMusic
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/2 17:35
	 */
	@PostMapping("addMusic")
	@ApiOperation("添加曲目（更新操作）")
	public R addMusic(@RequestBody MisMusic misMusic) {

		if (misMusic.getId() == null || "".equals(misMusic.getId())) {
			return new R(CommonConstants.FAIL, "请先上传曲目资源", false);
		}

		return new R(misMusicService.addMusic(misMusic));
	}

	/**
	 * 获取曲目
	 *
	 * @param collectionId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/4/27 11:01
	 */
	@GetMapping("getMusic")
	@ApiOperation(value = "获取曲目")
	public R getMusic(Integer collectionId, Integer current, Integer size) {

		//初始化结果集
		Map<String, Object> resultMap = MapUtil.newHashMap();
		//获取登录信息
		ShyMember member = SecurityUtils.getMember();
		if (collectionId != null) {
			//检索曲集信息
			MisMusicCollection misMusicCollection = misMusicCollectionService.getById(collectionId);
			//封面图片
			resultMap.put("collectionImg", misMusicCollection.getImg());
			//曲集名称
			resultMap.put("collectionName", misMusicCollection.getName());
			//作者
			resultMap.put("collectionAuthor", misMusicCollection.getPublisher());
			//简介
			resultMap.put("collectionIntroduction", misMusicCollection.getIntroduction());
			//曲集价格
			resultMap.put("collectionPrice", misMusicCollection.getTollAmount());
			//判断该用户是否购买曲集

			//判断是否已经在购物车内
			if (SecurityUtils.getMember() == null) {
				resultMap.put("cartStatus", 0);
			} else {
				resultMap.put("cartStatus", collectionMapper.checkCartStatus(SecurityUtils.getMember().getId(), collectionId));
			}

			if (member == null) {
				resultMap.put("isBuy", false);
			} else {
				resultMap.put("isBuy", buyCollectionService.list(new QueryWrapper<MisUserBuyCollection>()
						.eq(MisUserBuyCollection.COL_COLLECTION_ID, collectionId)
						.and(x -> x.eq(MisUserBuyCollection.COL_MEMBER_ID, member.getId()))).size() != 0);
			}

			resultMap.put("isSave", false);

			if (member != null) {
				//是否收藏
				resultMap.put("isSave", checkUserCollection(collectionId, member.getId()));
			}
		}

		//分页获取曲目列表
		Page page = new Page(current, size);

		IPage<MisMusicVO> misMusicIPage = null;

		if (collectionId == null) {
			misMusicIPage = userMusicService.getUserMusic(page, member.getId(), "1");
		} else {
			//分页查询
			misMusicIPage = misMusicService.getMusicPage(page, collectionId);
		}

		//2021/03/26 更新，有声图书扫码的场合，vip 字段不显示
		if ((boolean) resultMap.get("isBuy")) {
			List<MisMusicVO> records = misMusicIPage.getRecords();
			records.forEach(x -> x.setMemberAuthority("0"));
			misMusicIPage.setRecords(records);
		}

		//分页数据
		resultMap.put("pageData", misMusicIPage);

		return new R(resultMap);
	}

	/**
	 * 通过Id获取曲目详情(移动端专用)
	 *
	 * @param musicId
	 * @param type    1-下载的场合
	 * @param type    2-在线课的场合
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/8/18 10:59
	 **/
	@GetMapping("getMusicById")
	@ApiOperation("通过Id获取曲目详情(移动端专用)")
	public R getMusicById(Integer musicId, String type, String isShare) {

		//下载场合请求判断
		if ("1".equals(type)) {
			//判断是否超出此月下载限制
			int downloadMp3Count = userMusicService.getDownloadMp3Count(SecurityUtils.getMember().getId());
			if (downloadMp3Count >= 300) {
				throw new BusinessException("您本月下载次数不足");
			}
		}

		//获取曲目详情
		MisMusic music = misMusicService.getById(musicId);

		if (SecurityUtils.getMember() != null) {

			if (!"2".equals(type)) {
				//判断该用户是否是VIP
				String memberId = SecurityUtils.getMember().getId();
				String isVip = misMusicService.checkIsVip(memberId);
				//是否是老师
				String isTeacher = misMusicService.getIsTeacher(memberId);
				//判断该曲目是否有 VIP 权限【会员权限（0：无会员权限，1：有会员权限）】
				if ("1".equals(music.getMemberAuthority()) && !"1".equals(type)) {

					//不是vip
					if (isVip == null && "0".equals(isTeacher)) {
						//在判断是否购买了此曲集
						MisUserBuyCollection buyCollection = buyCollectionService.getOne(new QueryWrapper<MisUserBuyCollection>()
								.eq(MisUserBuyCollection.COL_COLLECTION_ID, music.getCollectionId())
								.and(x -> x.eq(MisUserBuyCollection.COL_MEMBER_ID, SecurityUtils.getMember().getId())));
						if (buyCollection == null) {
							return new R(CommonConstants.FAIL, "此曲目为VIP曲目，请到个人中心购买VIP或者购买单本曲集", false);
						}
					}
				}

				if ("1".equals(type)) {
					//不是vip
					if (isVip == null && "0".equals(isTeacher)) {
						//在判断是否购买了此曲集
						MisUserBuyCollection buyCollection = buyCollectionService.getOne(new QueryWrapper<MisUserBuyCollection>()
								.eq(MisUserBuyCollection.COL_COLLECTION_ID, music.getCollectionId())
								.and(x -> x.eq(MisUserBuyCollection.COL_MEMBER_ID, SecurityUtils.getMember().getId())));
						if (buyCollection == null) {
							return new R(CommonConstants.FAIL, "此曲目需要您购买过或者是VIP才能下载", false);
						}
					}
				}
			}


		} else {
			if ("1".equals(music.getMemberAuthority()) && isShare == null) {
				return new R(CommonConstants.FAIL, "请先登录", false);
			}
		}

		//获取私有文件路径
		music.setSvgFile(minioTemplate.getPrivateDownloadUrl(music.getSvgFile()));

		//将http协议修改为https协议返回前端
		String jsonUrl = minioTemplate.getPrivateDownloadUrl(music.getJsonFile());

		if (StringUtils.isEmpty(jsonUrl)) {
			throw new BusinessException("Json文件缺失，曲目ID：" + music.getId());
		}

		String jsonUrlResult = jsonUrl.replace("http", "https");

		if (StringUtils.isEmpty(jsonUrlResult)) {
			jsonUrlResult = jsonUrl;
		}

		music.setJsonFile(jsonUrlResult);

		if (music.getMp3File() != null) {
			music.setMp3File(minioTemplate.getPrivateDownloadUrl(music.getMp3File()));
		}

		if (music.getMvFile() != null) {
			music.setMvFile(minioTemplate.getPrivateDownloadUrl(music.getMvFile()));
		}

		MusicVO musicVO = new MusicVO();

		BeanUtils.copyProperties(music, musicVO);

		//是否收藏
		if (SecurityUtils.getMember() != null) {
			List<MisUserMusic> list = userMusicService.list(new QueryWrapper<MisUserMusic>()
					.eq(MisUserMusic.COL_TYPE, "1")
					.and(x -> x.eq(MisUserMusic.COL_DEL_FLAG, CommonConstants.STATUS_NORMAL))
					.and(y -> y.eq(MisUserMusic.COL_MEMBER_ID, SecurityUtils.getMember().getId()))
					.and(z -> z.eq(MisUserMusic.COL_MUSIC_ID, musicId)));
			if (list.size() > 0) {
				musicVO.setIsSave(true);
			} else {
				musicVO.setIsSave(false);
			}
		}

		return new R(musicVO);
	}

	/**
	 * 通过Id获取曲目详情(移动端专用)
	 *
	 * @param musicId
	 * @param type    1-下载的场合
	 * @param type    2-在线课的场合
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/8/18 10:59
	 **/
	@GetMapping("getMusicByIdV2")
	@ApiOperation("通过Id获取曲目详情(移动端专用)")
	public R getMusicByIdV2(String musicId, String type, String isShare) {

		if (StringUtils.isBlank(musicId) || "null".equals(musicId)) {
			return new R(new MusicVO());
		}
		Integer musicIdInt = Integer.valueOf(musicId);

		//下载场合请求判断
		if ("1".equals(type)) {
			//判断是否超出此月下载限制
			int downloadMp3Count = userMusicService
					.getDownloadMp3Count(SecurityUtils.getMember().getId());
			if (downloadMp3Count >= 300) {
				throw new BusinessException("您本月下载次数不足");
			}
		}

		//获取曲目详情
		MisMusic music = misMusicService.getById(musicIdInt);

		//获取私有文件路径
		music.setSvgFile(minioTemplate.getPrivateDownloadUrl(music.getSvgFile()));

		//将http协议修改为https协议返回前端
		String jsonUrl = minioTemplate.getPrivateDownloadUrl(music.getJsonFile());

		if (StringUtils.isEmpty(jsonUrl)) {
			throw new BusinessException("Json文件缺失，曲目ID：" + music.getId());
		}

		String jsonUrlResult = jsonUrl.replace("http", "https");

		if (StringUtils.isEmpty(jsonUrlResult)) {
			jsonUrlResult = jsonUrl;
		}

		music.setJsonFile(jsonUrlResult);

		if (music.getMp3File() != null) {
			music.setMp3File(minioTemplate.getPrivateDownloadUrl(music.getMp3File()));
		}

		if (music.getMvFile() != null) {
			music.setMvFile(minioTemplate.getPrivateDownloadUrl(music.getMvFile()));
		}

		MusicVO musicVO = new MusicVO();

		BeanUtils.copyProperties(music, musicVO);
		//默认可以播放
		musicVO.setOkPlay(true);
		//是否收藏
		if (SecurityUtils.getMember() != null) {
			List<MisUserMusic> list = userMusicService.list(new QueryWrapper<MisUserMusic>()
					.eq(MisUserMusic.COL_TYPE, "1")
					.and(x -> x.eq(MisUserMusic.COL_DEL_FLAG, CommonConstants.STATUS_NORMAL))
					.and(y -> y.eq(MisUserMusic.COL_MEMBER_ID, SecurityUtils.getMember().getId()))
					.and(z -> z.eq(MisUserMusic.COL_MUSIC_ID, musicIdInt)));
			if (list.size() > 0) {
				musicVO.setIsSave(true);
			} else {
				musicVO.setIsSave(false);
			}
		}

		//是否可以播放
		if (SecurityUtils.getMember() != null) {

			if (!"2".equals(type)) {
				//判断该用户是否是VIP
				String memberId = SecurityUtils.getMember().getId();
				String isVip = misMusicService.checkIsVip(memberId);
				//是否是老师
				String isTeacher = misMusicService.getIsTeacher(memberId);
				//判断该曲目是否有 VIP 权限【会员权限（0：无会员权限，1：有会员权限）】
				if ("1".equals(music.getMemberAuthority()) && !"1".equals(type)) {

					//不是vip
					if (isVip == null && "0".equals(isTeacher)) {
						//在判断是否购买了此曲集
						MisUserBuyCollection buyCollection = buyCollectionService
								.getOne(new QueryWrapper<MisUserBuyCollection>()
										.eq(MisUserBuyCollection.COL_COLLECTION_ID,
												music.getCollectionId())
										.and(x -> x.eq(MisUserBuyCollection.COL_MEMBER_ID,
												SecurityUtils.getMember().getId())));
						if (buyCollection == null) {
							musicVO.setOkPlay(false);
						}
					}
				}

				if ("1".equals(type)) {
					//不是vip
					if (isVip == null && "0".equals(isTeacher)) {
						//在判断是否购买了此曲集
						MisUserBuyCollection buyCollection = buyCollectionService
								.getOne(new QueryWrapper<MisUserBuyCollection>()
										.eq(MisUserBuyCollection.COL_COLLECTION_ID,
												music.getCollectionId())
										.and(x -> x.eq(MisUserBuyCollection.COL_MEMBER_ID,
												SecurityUtils.getMember().getId())));
						if (buyCollection == null) {
							musicVO.setOkPlay(false);
						}
					}
				}
			}

			//弹奏此曲目的最高分
			Integer bestScore = starMapper.getBestScoreByMemberId(SecurityUtils.getMember().getId(), musicId);
			musicVO.setBestScore(bestScore);

		} else {
			if ("1".equals(music.getMemberAuthority()) && isShare == null) {
				return new R(CommonConstants.FAIL, "请先登录", false);
			}
		}

		//新增曲集封面，曲集价格，曲集名称
		MisMusicCollection misMusicCollection = collectionMapper.selectById(musicVO.getCollectionId());
		musicVO.setCollImg(misMusicCollection.getImg());
		musicVO.setCollName(misMusicCollection.getName());
		if (misMusicCollection.getTollAmount() != null) {
			musicVO.setCollPrice(misMusicCollection.getTollAmount().toString());
		}
		return new R(musicVO);
	}

	/**
	 * 保存曲目播放记录
	 *
	 * @param musicId
	 * @return
	 * @author nianhua.jiang
	 * @date 2021/4/8 17:34
	 **/
	@GetMapping("addRecentPlayData")
	public R addRecentPlayData(String musicId) {

		if (StringUtils.isBlank(musicId) || "null".equals(musicId)) {
			return new R(true);
		}
		Integer musicIdInt = Integer.valueOf(musicId);

		if (SecurityUtils.getMember() != null) {
			addToRecentPlayList(musicIdInt, SecurityUtils.getMember().getId());
		}
		return new R(true);
	}

	private void addToRecentPlayList(Integer musicId, String memberId) {

		//检测是否有此首曲目，如果有，将曲目加到最新
		MisRecentPlayed existing = recentPlayedMapper.selectOne(
				new QueryWrapper<MisRecentPlayed>().eq("member_id", memberId).eq("music_id", musicId));

		if (existing != null) {
			existing.setLastPlaytime(LocalDateTime.now());
			existing.setTotalTimes(existing.getTotalTimes() + 1);
			recentPlayedMapper.updateById(existing);
		} else {
			//看该用户曲目是否超过30首
			List<MisRecentPlayed> memberList = recentPlayedMapper.selectList(
					new QueryWrapper<MisRecentPlayed>().eq("member_id", memberId).orderByDesc("last_playtime"));

			if (memberList.size() >= 30) {
				//删除用户播放列表lastPlayTime最早的那个
				recentPlayedMapper.deleteById(memberList.get(memberList.size() - 1).getId());
			}

			MisRecentPlayed entity = new MisRecentPlayed();
			entity.setMemberId(memberId);
			entity.setMusicId(musicId);
			entity.setLastPlaytime(LocalDateTime.now());
			entity.setTotalTimes(1);
			recentPlayedMapper.insert(entity);
		}
	}

	@GetMapping("getRecentMusic")
	@ApiOperation("获取最近播放30曲目")
	public R getRecentMusic() {
		return new R(recentPlayedMapper.getRecentMusic(SecurityUtils.getMember().getId()));
	}

	@GetMapping("getRecentMusicV2")
	@ApiOperation("获取最近播放30曲目（排行榜业务）")
	public R getRecentMusicV2() {

		//先定义响应体 map
		Map<String, Object> resMap = new HashMap<>(3);
		//用户ID
		String memberId = SecurityUtils.getMember().getId();
		//定义满分星总数
		Integer fullMarkStarAll = 0;
		//定义勤奋星总数
		Integer hardworkingStarAll = 0;
		//查询曲目历史播放记录
		List<MisRecentPlayedVO> recentMusic = recentPlayedMapper.getRecentMusic(memberId);
		//循环查询每个曲目的条数
		List<MisMusicMemberStar> misMusicMemberStars = starMapper.getStarCountByMemberId(memberId);

		if (CollectionUtils.isNotEmpty(misMusicMemberStars)) {
			//分组装载 key = music value = 两种星星的数量
			Map<Integer, MisMusicMemberStar> totalTimesGroup = misMusicMemberStars.stream()
					.collect(Collectors.toMap(MisMusicMemberStar::getMusicId, item -> item, (k1, k2) -> k1));
			//循环赋值
			for (MisRecentPlayedVO misRecentPlayedVO : recentMusic) {
				MisMusicMemberStar misMusicMemberStar = totalTimesGroup.get(misRecentPlayedVO.getId());
				if (misMusicMemberStar != null) {
					misRecentPlayedVO.setFullMarkStar(misMusicMemberStar.getFullMarkStar());
					misRecentPlayedVO.setHardworkingStar(misMusicMemberStar.getHardworkingStar());
				}
			}
			//计算满分星总数
			fullMarkStarAll = misMusicMemberStars.stream().collect(Collectors.summingInt(MisMusicMemberStar::getFullMarkStar));
			//计算勤奋星总数
			hardworkingStarAll = misMusicMemberStars.stream().collect(Collectors.summingInt(MisMusicMemberStar::getHardworkingStar));

		}
		resMap.put("hardworkingStarAll", hardworkingStarAll);
		resMap.put("fullMarkStarAll", fullMarkStarAll);
		resMap.put("resultList", recentMusic);
		return new R(resMap);
	}

	/**
	 * 删除曲目信息
	 *
	 * @param musicId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/7 15:16
	 */
	@GetMapping("delMusic")
	@ApiOperation("删除曲目信息")
	public R delMusic(Integer musicId) {

		//获取此条数据
		MisMusic misMusic = misMusicService.getById(musicId);
		//将其设置成【已删除】
		misMusic.setDelFlag(CommonString.DELETE_FLG_DEL);
		//返回执行结果
		return new R(misMusicService.updateById(misMusic));

	}

	/**
	 * 更新Music
	 *
	 * @param music
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/7 15:16
	 */
	@GetMapping("updateById")
	@ApiOperation("删除曲目信息")
	public R updateById(@RequestBody MisMusic music) {
		//返回执行结果
		return new R(misMusicService.updateById(music));
	}

	/**
	 * 收藏/取消收藏 曲目（我喜欢）
	 *
	 * @param map
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/7 17:27
	 */
	@PostMapping("userMusic")
	@ApiOperation("收藏/取消收藏 曲目（我喜欢）")
	public R userMusic(@RequestBody Map<String, Object> map) {

		//0-添加收藏/下载，1-移除收藏/下载
		String delFlag = (String) map.get("delFlag");
		//曲目ID
		List<Integer> musicIdArr = (List<Integer>) map.get("musicId");
		//type 类型
		String type = (String) map.get("type");
		//user_id
		String userId = SecurityUtils.getMember().getId();

		for (Integer musicId : musicIdArr) {
			//收藏
			if ("0".equals(delFlag)) {

				//如果类型为下载
				if ("2".equals(type)) {
					//判断是否超出此月下载限制
					int downloadMp3Count = userMusicService.getDownloadMp3Count(SecurityUtils.getMember().getId());
					if (downloadMp3Count >= 300) {
						throw new BusinessException("您本月下载次数不足");
					}
				}

				//判断是否已经存在
				MisUserMusic misUserMusicOld = userMusicService.getOne(new QueryWrapper<MisUserMusic>()
						.eq(MisUserMusic.COL_MUSIC_ID, musicId)
						.and(x -> x.eq(MisUserMusic.COL_MEMBER_ID, SecurityUtils.getMember().getId()))
						.and(y -> y.eq(MisUserMusic.COL_TYPE, type)));

				//如果此曲目添加过，更新状态
				if (misUserMusicOld != null) {
					misUserMusicOld.setDelFlag(delFlag);
					userMusicService.updateById(misUserMusicOld);
				}

				//如果此曲目没被添加过，则新建
				else {
					MisUserMusic misUserMusic = new MisUserMusic();
					//用户ID
					misUserMusic.setMemberId(userId);
					//曲目ID
					misUserMusic.setMusicId(musicId);
					//类型( 1-收藏 2-下载）
					misUserMusic.setType(type);
					//逻辑删除（0：未删除，1：已删除）
					misUserMusic.setDelFlag(delFlag);
					//创建时间
					misUserMusic.setCreateTime(new Date());
					//创建人
					misUserMusic.setCreateUser(userId);
					//更新时间
					misUserMusic.setUpdateTime(new Date());
					//更新人
					misUserMusic.setUpdateUser(userId);
					userMusicService.save(misUserMusic);
				}
			}

			//取消收藏
			else if ("1".equals(delFlag)) {
				QueryWrapper<MisUserMusic> queryWrapper = new QueryWrapper<>();
				//曲目ID
				queryWrapper.eq(MisUserMusic.COL_MUSIC_ID, musicId);
				//用户ID
				queryWrapper.eq(MisUserMusic.COL_MEMBER_ID, userId);
				//类型：收藏
				queryWrapper.eq(MisUserMusic.COL_TYPE, CommonString.USER_MUSIC_TYPE_SAVE);
				userMusicService.remove(queryWrapper);
			}

			//delflag 参数不正确
			else {
				return new R<>(CommonConstants.FAIL, "flg参数不正确");
			}
		}

		return new R(CommonConstants.SUCCESS, "操作成功", true);

	}

	/**
	 * 查询该曲目是否存入【我喜欢】
	 *
	 * @param musicId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/7 18:05
	 */
	@GetMapping("checkUserMusic")
	@ApiOperation("查询该曲目是否存入【我喜欢】")
	public R checkUserMusic(Integer musicId) {

		String userId = SecurityUtils.getMember().getId();

		QueryWrapper<MisUserMusic> queryWrapper = new QueryWrapper<>();

		//用户ID
		queryWrapper.eq(MisUserMusic.COL_MEMBER_ID, userId);
		//曲目ID
		queryWrapper.eq(MisUserMusic.COL_MUSIC_ID, musicId);
		//逻辑删除
		queryWrapper.eq(MisUserMusic.COL_DEL_FLAG, CommonString.DELETE_FLG);
		//查询
		List<MisUserMusic> list = userMusicService.list(queryWrapper);
		//如果存在则已经保存到【我喜欢】中
		if (list.size() > 0) {
			return new R<>(true, "已保存到我喜欢");
		}
		return new R<>(false, "未保存到我喜欢");
	}


	/**
	 * 分页查询我的收藏/我的下载
	 *
	 * @param current
	 * @param size
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/8 9:43
	 */
	@ApiOperation("分页查询我的收藏/我的下载")
	@GetMapping("getUserMusic")
	public R getUserMusic(Integer current, Integer size, String type) {

		//获取 user_id
		String userId = SecurityUtils.getMember().getId();
		//分页参数
		Page page = new Page(current, size);
		//分页查询
		IPage<MisMusicVO> userMusicList = userMusicService.getUserMusic(page, userId, type);

		return new R(userMusicList);
	}

	/**
	 * 书籍配套资源
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/9 14:33
	 */
	@GetMapping("getMusicResources")
	@ApiOperation("书籍配套资源")
	public R getMusicResources(Integer current, Integer size) {

		//分页对象
		Page page = new Page(current, size);
		//查询曲目存在mp3或者mv资源的曲目
		QueryWrapper<MisMusic> misMusicQueryWrapper = new QueryWrapper<>();
		misMusicQueryWrapper.ne(MisMusic.COL_MP3_FILE, CommonString.EMPTY).or(x -> x.ne(MisMusic.COL_MV_FILE, CommonString.EMPTY));

		return new R(misMusicService.page(page, misMusicQueryWrapper));
	}

	/**
	 * 查询有伴奏的曲目
	 *
	 * @param current
	 * @param size
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/9 16:47
	 */
	@GetMapping("getKalaMusic")
	@ApiOperation("查询有伴奏的曲目")
	public R getKalaMusic(Integer current, Integer size) {
		//分页参数
		Page page = new Page(current, size);
		return new R(
				misMusicService.page(page, new QueryWrapper<MisMusic>().eq(MisMusic.COL_KALA_STATUS, CommonString.KALA_STATUS_YES)));
	}

	/**
	 * 获取4个标签上的各分类个数
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/17 10:46
	 */
	@ApiOperation("获取4个标签上的各分类个数")
	@GetMapping("getCount")
	public R getCount() {

		//创建结果集
		Map<String, Object> resultMap = MapUtil.newHashMap(4);

		//获取member_id
		String memberId = SecurityUtils.getMember().getId();

		//我喜欢数量
		resultMap.put("myLikeMusicCount", userMusicService.count(new QueryWrapper<MisUserMusic>()
				.eq(MisUserMusic.COL_MEMBER_ID, memberId)
				.and(x -> x.eq(MisUserMusic.COL_DEL_FLAG, CommonString.DELETE_FLG))
				.and(y -> y.eq(MisUserMusic.COL_TYPE, CommonString.USER_MUSIC_TYPE_SAVE))));

		//收藏曲集的数量
		resultMap.put("mySaveCollCount", userCollectionService.getCount(memberId));

		//自建曲集的数量
		resultMap.put("myCollCount", myCollectionService.count(new QueryWrapper<MisMyCollection>()
				.eq(MisMyCollection.COL_MEMBER_ID, memberId)
				.and(x -> x.eq(MisMyCollection.COL_DEL_FLAG, CommonString.DELETE_FLG))));
		//有声图书的数量
		resultMap.put("mySoundBookCount", misMusicCollectionService.getMySoundBook(new Page()).getTotal());

		return new R(resultMap);
	}

	/**
	 * 查询曲集是否已经收藏
	 *
	 * @param collectionId 曲集ID
	 * @param userId       用户ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/8 10:27
	 */
	private boolean checkUserCollection(Integer collectionId, String userId) {

		QueryWrapper<MisUserCollection> queryWrapper = new QueryWrapper<>();

		//用户ID
		queryWrapper.eq(MisUserCollection.COL_MEMBER_ID, userId);
		//曲集ID
		queryWrapper.eq(MisUserCollection.COL_COLLECTION_ID, collectionId);
		//逻辑删除
		queryWrapper.eq(MisUserCollection.COL_DEL_FLAG, CommonString.DELETE_FLG);
		//查询
		List<MisUserCollection> list = userCollectionService.list(queryWrapper);
		//如果存在则已经保存到【我喜欢】中
		if (list.size() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 获取播放器内【添加到列表】
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/30 17:51
	 */
	@GetMapping("getAddList")
	@ApiOperation("获取播放器内【添加到】列表")
	public R getAddList() {

		//获取memberId
		String memberId = SecurityUtils.getMember().getId();

		List<AddListVO> addListVO = new ArrayList<AddListVO>();

		AddListVO addList = new AddListVO();
		//固定传【我喜欢】相关参数
		addList.setImgUrl("");
		addList.setMusicCount(userMusicService.count(new QueryWrapper<MisUserMusic>()
				.eq(MisUserMusic.COL_MEMBER_ID, memberId)
				.and(x -> x.eq(MisUserMusic.COL_DEL_FLAG, CommonString.DELETE_FLG))
				.and(y -> y.eq(MisUserMusic.COL_TYPE, CommonString.USER_MUSIC_TYPE_SAVE))));
		addList.setMyCollectionId(0);
		addList.setMyCollectionName("单曲收藏");
		addListVO.add(addList);

		//获取自建曲集的相关信息
		List<MyCollectionVO> myCollectionVOList = myCollectionService.getMyCollection(memberId);
		//自建曲集相关数据
		for (MyCollectionVO myCollectionVO : myCollectionVOList) {
			AddListVO addList2 = new AddListVO();
			//图片路径
			addList2.setImgUrl(myCollectionVO.getImg());
			//歌曲数量
			addList2.setMusicCount(myCollectionVO.getMusicCount());
			//曲集名称
			addList2.setMyCollectionName(myCollectionVO.getName());
			//曲集ID
			addList2.setMyCollectionId(myCollectionVO.getId());
			addListVO.add(addList2);
		}
		return new R(addListVO);
	}

	/**
	 * 获取曲目详情（后台管理用）
	 *
	 * @param musicId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/30 18:32
	 */
	@GetMapping("getMusicDetail")
	@ApiOperation("获取曲目详情（后台管理用）")
	public R getMusicDetail(Integer musicId) {

		//根据曲目ID获取曲集id
		MisMusic music = misMusicService.getById(musicId);
		FileInfo[] allObjectsByPrefix = null;
		if (null != music.getOssFile() && !music.getOssFile().isEmpty()) {
			allObjectsByPrefix = minioTemplate.getAllObjectsByPrefix("mido-songbook-sourcefile", music.getOssFile(), true);
		}
		Map<String, Object> resultMap = MapUtil.newHashMap();

		resultMap.put("musicDetail", music);
		resultMap.put("fileDetail", allObjectsByPrefix);

		return new R(resultMap);
	}

	/**
	 * 后台获取曲目信息
	 *
	 * @param current
	 * @param size
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/2 18:55
	 */
	@GetMapping("getMusicList")
	public R getMusic(Integer current, Integer size,
					  String name, String status,
					  String memberAuthority,
					  Integer id, Integer collectionId) {

		//分页参数
		Page page = new Page(current, size);
		//int intId = 0;
		//try {
		//intId = Integer.parseInt(id);
		//} catch (Exception e) {
		//}

		return new R(misMusicService.getMusicList(page, name, status, memberAuthority, id, collectionId));
	}

	@GetMapping("getMusicDeleteList")
	public R getMusicDeleteList(Integer current, Integer size,
								String name, String status,
								String memberAuthority,
								Integer id, Integer collectionId) {

		//分页参数
		Page page = new Page(current, size);

		return new R(musicMapper.getMusicDeleteList(page, name, status, memberAuthority, id, collectionId));
	}

	@ApiOperation("获取大厅曲库大全上的4个标签数量")
	@GetMapping("getAllCount")
	public R getAllCount() {

		Map<String, Integer> resultMap = MapUtil.newHashMap();

		//乐团伴奏
		Integer kalaCount = misMusicService.count(new QueryWrapper<MisMusic>()
				.eq(MisMusic.COL_KALA_STATUS, "1")
				.and(x -> x.eq(MisMusic.COL_STATUS, "0"))
				.and(y -> y.eq(MisMusic.COL_DEL_FLAG, "0")));
		resultMap.put("kalaCount", kalaCount);

		//书籍配套资源
		List<MisMusic> musics = misMusicService.getResouresCount();
		int resouresCount = 0;
		for (MisMusic music : musics) {
			if (music.getMp3File() != null) {
				resouresCount++;
			}
			if (music.getMvFile() != null) {
				resouresCount++;
			}
		}
		resultMap.put("resouresCount", resouresCount);

		//正版教材数量
		Integer collectionCount = misMusicCollectionService.count(new QueryWrapper<MisMusicCollection>()
				.eq(MisMusicCollection.COL_DEL_FLAG, "0"));
		resultMap.put("collectionCount", collectionCount);
		//数字曲谱数量
		Integer musicCount = misMusicService.count(new QueryWrapper<MisMusic>()
				.eq(MisMusic.COL_DEL_FLAG, "0")
				.and(x -> x.eq(MisMusic.COL_FILE_STATUS, "1")));
		resultMap.put("musicCount", musicCount);

		return new R(resultMap);

	}

	@PostMapping("updateMusic")
	@ApiOperation("更新曲目")
	public R updateMusic(@RequestBody MisMusic music) {

		MisMusic misMusic = misMusicService.getById(music.getId());
		//曲目名称
		misMusic.setName(music.getName());
		//曲集ID
		misMusic.setCollectionId(music.getCollectionId());
		//排序
		misMusic.setSort(music.getSort());
		//权限
		misMusic.setMemberAuthority(music.getMemberAuthority());
		misMusic.setKalaSpeed(music.getKalaSpeed());
		misMusic.setKalaStartTime(music.getKalaStartTime());
		misMusic.setFileStatus(music.getFileStatus());
		//音色midi
		misMusic.setPcmidi(music.getPcmidi());
		//伴奏midi
		misMusic.setBgmidi(music.getBgmidi());
		misMusic.setKalaStatus(music.getKalaStatus());
		return new R(misMusicService.updateById(misMusic));
	}

	/**
	 * 启用/禁用曲目
	 *
	 * @param musicId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/7 15:36
	 */
	@GetMapping("forbiddenMusic")
	@ApiOperation("启用/禁用曲目")
	public R forbiddenMusic(Integer musicId, String status) {

		MisMusic misMusic = misMusicService.getById(musicId);

		misMusic.setStatus(status);

		return new R(misMusicService.updateById(misMusic));
	}

	/**
	 * 根据MusicId获取有效曲目详情（后台管理用）
	 *
	 * @param musicId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/30 18:32
	 */
	@GetMapping("getById")
	@ApiOperation("根据musicId获取曲目详情（后台管理用）")
	public R getById(Integer musicId) {
		MisMusic misMusic = misMusicService.getValidMusicById(musicId);

		//根据曲目ID获取曲目实体数据
		return misMusic == null ?
				new R<>(CommonConstants.FAIL,
						"未找到对应曲目，请确定曲目是否有效", false) : new R(misMusic);
	}

	/**
	 * 下载MP3成功回调接口
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/9/1 2:11
	 **/
	@GetMapping("downloadMp3Success")
	public R downloadMp3Success() {
		return new R(misMusicService.downloadMp3Success());
	}

	/**
	 * 获取引导视频
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/9/22 9:56
	 **/
	@GetMapping("getGuideVideo")
	public R getGuideVideo() {
		return new R(guideVideoService.list(new QueryWrapper<MisGuideVideo>().eq(MisGuideVideo.COL_STATUS, "0")));
	}

	/**
	 * @param id
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/10/19 19:52
	 **/
	@GetMapping("checkMusicIsBuy")
	public R checkMusicIsBuy(Integer id) {

		MisMusic music = misMusicService.getById(id);

		if (SecurityUtils.getMember() == null) {
			return new R(false);
		} else {
			return new R(buyCollectionService.getOne(new QueryWrapper<MisUserBuyCollection>()
					.eq(MisUserBuyCollection.COL_COLLECTION_ID, music.getCollectionId())
					.and(x -> x.eq(MisUserBuyCollection.COL_MEMBER_ID, SecurityUtils.getMember().getId()))) != null);
		}

	}

	/**
	 * 小程序端获取曲目列表
	 *
	 * @param current
	 * @param size
	 * @param type
	 * @param myCollectionId
	 * @param collectionId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/11/28 13:36
	 **/
	@GetMapping("getMusicListByMini")
	public R getMusicListByMini(Integer current, Integer size, String type, Integer myCollectionId, Integer collectionId) {

		Page page = new Page(current, size);

		IPage<MisMusicVO> userMusic = null;

		if (type == null) {
			return new R(CommonConstants.FAIL, "type参数不能为空", false);
		}

		if ("0".equals(type)) {
			userMusic = userMusicService.getUserMusic(page, SecurityUtils.getMember().getId(), "1");
		}

		if ("1".equals(type)) {
			if (myCollectionId == null) {
				return new R(CommonConstants.FAIL, "类型为自建曲集时，自建曲集ID不能为空", false);
			}
			userMusic = misMyCollectionMusicService.getMyMusic(new Page(current, size), myCollectionId);
		}

		if ("2".equals(type)) {
			if (collectionId == null) {
				return new R(CommonConstants.FAIL, "类型为收藏曲集时，收藏曲集ID不能为空", false);
			}
			userMusic = misMusicService.getMusicPage(page, collectionId);
		}
		return new R(userMusic);
	}

	@GetMapping("getSvgUrls")
	public R getSvgUrls(Integer musicId) {

		MisMusic music = misMusicService.getById(musicId);

		String ossfile = music.getOssFile();

		FileInfo[] fileInfos = minioTemplate.getAllObjectsByPrefix("mido-songbook-sourcefile", ossfile, true);

		List<String> svgPublic = new ArrayList<>();

		for (FileInfo fileInfo : fileInfos) {
			if (fileInfo.key.endsWith("svg")) {
				svgPublic.add("http://sourcefile.joymido.com/" + fileInfo.key);
			}
		}

		List<String> svgPrivate = new ArrayList<>();

		for (String svgUrl : svgPublic) {
			String privateDownloadUrl = minioTemplate.getPrivateDownloadUrl(svgUrl);
			svgPrivate.add(privateDownloadUrl);
		}

		return new R(svgPrivate);

	}

}
